# Create your views here.
import copy

import os
import re
from threading import Thread

from django.http import JsonResponse

from django.views import View
from django.shortcuts import render
from django.views.decorators.http import require_POST, require_GET

from werkzeug.utils import secure_filename

from djangoProject.settings import BASE_DIR

from django.urls import reverse
from django.shortcuts import redirect

from .models import FilesPath, JobConfig, MenuInfo
from job.src.application.SchedulerFlow import SchedulerJobs
from job.src.function.multi_threadop import stop_thread

from job.src.function.record_log import mylog
from job.src.function.basic_opration import read_file, write_file, get_curtime, read_csv, list_to_dic, delete_file
from job.src.function.strencode import str_decode, str_encoe
from upgradeTool.src.application.flask_demo import run_flask_forward
from .src.application.reload import reload
from .src.function.dataoperation import loadYaml

sheduler = SchedulerJobs()
webPage = sheduler.webPage

def main(request):
    mylog.info(f'Enter MainPage!')
    reload()
    menuInfo = MenuInfo.objects.filter(list_flag=True).values()
    # mylog.info(f"menuInfo: {menuInfo}")
    newList = []
    for unit in list(menuInfo):
        unit['funList'] = unit['func_desc'].split(';') if unit['func_desc'] else []
        unit['remarkList'] = unit['remarks'].split(';') if unit['remarks'] else []
        newList.append(unit)
    webPage['menuList'] = newList
    mylog.info(newList)
    return render(request, 'mainPage.html', webPage)


# --------------------------------edit_text.html-----------------------------------------

class Modify(View):
    op_types = ['Get_ConfigInfo', 'Modify_ConfigInfo']
    # files = dj_config['edit_files']
    context = {}
    context.update(webPage)
    context['op_types'] = op_types
    context['has_permission'] = True
    def get(self, request):
        files = FilesPath.objects.filter(space='edit_files').values('id', 'upload_file', 'cn_name')
        self.context.update({"filenames": list(files)})                #['filenames'] = list(files)
        return render(request, "edit_text.html", self.context)

    def post(self, request):
        num = request.POST.get('config_filename')
        op_type = request.POST.get('op_type')
        files = self.context.get('filenames', None)
        new_files, tar_dic = self.data_operate(files, int(num))
        self.context['filenames'] = new_files
        filename = tar_dic.get('upload_file')
        if not os.path.isabs(filename):
            filename = os.path.join(BASE_DIR, filename)
        if op_type == 'Get_ConfigInfo':
            content = '\n' + read_file(filename)
        elif op_type == 'Modify_ConfigInfo':
            content = request.POST.get('content')
            write_file(filepath=filename, content=content)
            content = '\n' + '提交成功！'
        else:
            content = '\n' + '操作失败，只支持Get_ConfigInfo和Modify_ConfigInfo！'
        self.context['content'] = content
        mylog.info(f"context: {self.context}")
        return render(request, "edit_text.html", self.context)

    def data_operate(self, files, num):
        new_files = []
        tar_dic = {"id": 0, "upload_file": "", "cn_name": "未找到"}
        for unit in files:
            if unit['id'] == num:
                tar_dic.update(unit)
            else:
                new_files.append(unit)
        new_files.insert(0, tar_dic)
        # print(new_files)
        return new_files, tar_dic

@require_POST
def data_encode(request):
    context = {}
    context.update(webPage)
    password = request.POST.get('password')
    res = str_encoe(password)
    content = f'\r\n加密后的字符串：{res}'
    context['content'] = content
    return render(request, 'edit_text.html', context)

def get_Job_Config():
    '''
    获取jobconfig的配置信息，返回调度任务所需的参数列表
    :return:
    '''
    jobConfig = []
    jobList = JobConfig.objects.filter(flag=1).values("id")
    for job in jobList:
        cur_id = job['id']
        # 查询出关联表的group的人员信息，并将其转化为字典 names_info
        job_0 = JobConfig.objects.filter(id=cur_id).first().group_id.exclude(group_id='None').values("user", "phone")
        group_dic = {unit['user']: unit['phone'] for unit in job_0} if job_0 else {}
        names_info = {"names_info": group_dic} if group_dic else {}
        # 根据id取出job的配置信息
        job_1 = JobConfig.objects.filter(id=cur_id).values()
        cur_job = list(job_1)[0] if job_1 else {}
        # 取出corn_time
        corn_time = {"days": cur_job.get("corn_day", "0-4"), "hour": cur_job.get("corn_hour", 8), "minute": cur_job.get("corn_min")}
        cur_job['corn_time'] = corn_time
        # 从job的配置信息取出 skip_date 字段信息，并转换成字典
        skip_date = cur_job.get('skip_date', None)
        mylog.info(f"skip_date: {skip_date}")
        skip_date_dic = {"skip_date": str(skip_date).replace('-', '')} if skip_date else {}
        # 从job的配置信息取出 params 字段信息，并转换成字典；将 skip_date 和 names_info 更新进去
        params = cur_job.get('param', None)
        params_dic = loadYaml(params) if params else {}
        mylog.info(f"params_dic: {params_dic}")
        params_dic.update(skip_date_dic)
        params_dic.update(names_info)
        new_params = {'param': params_dic}
        # 更新params 添加到列表中
        cur_job.update(new_params)
        mylog.info(f"cur_job: {cur_job}")
        jobConfig.append(cur_job)
    return jobConfig

# 获取调度的任务信息
def getJobConfig(request):
    context = {}
    jobConfig = get_Job_Config()
    context['job'] = jobConfig
    return JsonResponse(context)

jobs_list = []
thread_list = []
@require_GET
def start_job(request):
    flag = request.GET.get('flag')
    job_name = request.GET.get('job_name')
    if flag == 'start':
        if job_name == 'schedule_job':
            if len(jobs_list) == 0:
                jobList = get_Job_Config()
                thread_01 = Thread(target=sheduler.start_jobs, args=(jobList,))
                thread_01.setName(job_name)
                thread_01.start()
                jobs_list.append(thread_01)
                return JsonResponse({"res": f'\r\n任务{job_name}启动了！\r\n'})
            else:
                return JsonResponse({"res": f'\r\n定时任务{job_name}已经启动过了，请勿重复启动！\r\n'})
        else:
            if len(thread_list) == 0:
                thread_02 = Thread(target=run_flask_forward)
                thread_02.setName(job_name)
                thread_02.start()
                thread_list.append(thread_02)
                return JsonResponse({"res": f'\r\n转发服务{job_name}启动了！\r\n'})
            else:
                return JsonResponse({"res": f'\r\n转发服务{job_name}已经启动过了，请勿重复启动！\r\n'})
    elif flag == 'end':
        if job_name == 'schedule_job':
            if len(jobs_list) > 0:
                try:
                    sheduler.stop_jobs()
                    jobs_list.pop(0)
                    stop_thread(jobs_list[0])
                except Exception as e:
                    mylog.error(e)
        else:
            if len(thread_list) > 0:
                # sheduler.pf.shut_process("5009")
                stop_thread(thread_list[0])
                thread_list.pop(0)
        return JsonResponse({"res": f'\r\n定时任务{job_name}已经中断！\r\n'})
    else:
        return JsonResponse({"res": '\r\n参数错误，flag=start/end！\r\n'})

# django数据库测试
@require_GET
def query_files(request):
    # space = request.GET.get('space')
    res_space = FilesPath.objects.filter(space='ljk').values()
    print("res_space:", res_space)
    return JsonResponse({"res_data": "successful"}) # "successful"



# --------------------------------jobs_config.html 该页面废弃-----------------------------------------
job_inf = sheduler.bscf
class JiraJob(View):
    tips_content = ''
    dic_res = {'id': '', 'fucName': '', 'corn_time': {'days': '', 'hour': '', 'minute': ''},
               'params': {'jira_login': {}, 'dd_info': {'dd_url': '', 'dd_tip': ''}, 'jsql': '', 'names_info': {}}}
    job_list = job_inf['jobs']
    type_list = [unit['fucName'] for unit in job_list]
    res_typey_list = list(set(type_list))
    def get(self, request):
        context = {}
        context.update(webPage)
        context['job_id'] = [unit['id'] for unit in self.job_list if unit['fucName'] == 'query_jira_info']
        return render(request, "jobs_config.html", context)

    def post(self, request):
        context = {}
        context.update(webPage)
        job_type = request.POST.get('job_type')
        job_id = request.POST.get('job_id')
        mylog.info(f'request.POST:{job_id}')
        if job_type == '0':
            new_dic = {'id': job_id}
            sheduler.update_job_config(new_job_dic=new_dic, flag=False)
            return redirect(reverse('job:jiar_modify'))
        else:
            if job_id == '0':
                tips = job_inf['help_doc']
                self.tips_content = '\n'.join(tips)
                context['res_content'] = self.tips_content
            elif job_id == '1':
                new_id = 'query_jira_info_' + get_curtime("%Y%m%d%H%M%S")
                self.dic_res.update({'id': new_id})
            else:
                for unit in self.job_list:
                    if unit['id'] == job_id:
                        raw_pw = unit['params'].get('jira_login', {}).get('password')
                        pw = str_decode(raw_pw)
                        updic = {'password': pw}
                        unit.update(updic)
                        self.dic_res = copy.deepcopy(unit)
        context['dic_res'] = self.dic_res
        return render(request, 'jobs_config.html', context)

@require_POST
def modify_job(request):
    context = {}
    context.update(webPage)
    job_list = job_inf['jobs']
    id_list = [unit['id'] for unit in job_list if unit['fucName'] == 'query_jira_info']
    job_type = request.POST.get('job_type')
    job_id = request.POST.get('job_id')
    is_update = request.POST.get('start_flag')
    is_update_bool = True if is_update == '1' else False
    time_fre = request.POST.get('time_fre')
    time_hour = request.POST.get('job_time_h')
    time_minter = request.POST.get('job_time_m')
    username = request.POST.get('jira_name')
    password = request.POST.get('jira_pw')
    pw_encode = str_encoe(password)
    jira_url = request.POST.get('jira_url')
    jara_dic = {'username': username, 'password': pw_encode, 'jira_url': jira_url}
    dd_url = request.POST.get('job_dd_url')
    dd_tip = request.POST.get('job_dd_tip')
    dd_info = {'dd_url': dd_url, 'dd_tip': dd_tip}
    jira_sql = request.POST.get('job_jira')
    if not re.search(r'reporter', jira_sql, re.I):
        jira_sql = jira_sql + ' AND reporter in ({})'
    file_dir = os.path.join(BASE_DIR, 'job/static/jira')
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    f = request.FILES.get('module_file', None)
    names_info = {}
    if f:
        filepath = f.filename
        fname = secure_filename(filepath)
        uploadfile = os.path.join(file_dir, fname)
        f.save(uploadfile)  # 保存文件到upload目录
        res_cons = read_csv(uploadfile)
        names_info = list_to_dic(res_cons[1:])
        mylog.info(f'res_dic:{names_info}')
        delete_file(uploadfile)
    dic_res = {'id': job_id, 'fucName': job_type, 'is_update': is_update_bool,
               'corn_time': {'days': time_fre, 'hour': time_hour, 'minute': time_minter},
               'params': {'jira_login': jara_dic, 'dd_info': dd_info, 'jsql': jira_sql, 'names_info': names_info}}
    web_dic = copy.deepcopy(dic_res)
    mylog.info(f'dic_res: {dic_res}')
    sheduler.update_job_config(dic_res)
    msg = f'添加或修改成功!'
    context['job_id'] = id_list
    context['dic_res'] = web_dic
    context['res_content'] = msg
    return render(request, 'jobs_config.html', context)

